var Person = (function (parent, $) {
    var my = parent.Person = parent.Person || {};
    my.wikid = function (results) {
        var img;
        if (results.doc)  {
            img = my.getImage(results.doc);
            //console.log(img);
            if (img) {
                $('.mainTopicImage').attr('src',img);
                //img.css({'position' : 'absolute', 'right' : '30px', 'top':'65px'});
            }
        }
    };

    my.edit = function(results) {
        if (results.isNew) {
            wikid.registerGenerateTopicId('Person', my.generateTopicId);
        }
        var selection = $('<div id="avatarSelection"></div>')
        .append('<b>Avatar Source</b><br/>')
        .append('<input type="radio" name="avatar" value="gravatar"> <a href="http://gravatar.com" target="_blank">Gravatar (default)</a><br/>')
        .append('<input type="radio" name="avatar" value="icon"> Attachment');
        $('#Person').append(selection);

    }

    my.generateTopicId = function() {
        var firstName = $('#inputid\\.json_root\\.first').val();
        var lastName = $('#inputid\\.json_root\\.lastName').val();
        return firstName + '_' + lastName;
    }

    my.getImage = function(doc) {

        var facebookDetails = wikid.getFacebookDetails(doc);
        // hack attack
        var db_name = wikid.parseDBname(window.location);

        if ( doc.Person && doc['_attachments'] && doc['_attachments']['-icon.jpg'])  {


            return '/'+ db_name + '/' + doc['_id'] +'/-icon.jpg';
        }
        else if (facebookDetails) {
            return facebookDetails.picture ;
        }
		else if (doc.Person && doc.Person.email) {
            var hash = $.md5($.trim(doc.Person.email).toLowerCase());
            return 'http://www.gravatar.com/avatar/' + hash + '?s=25&d=wavatar';

        }
        return 'images/anon.jpg';

    }

    return parent;
}(wikid || {}, jQuery));